<?php
// -----------------------------------------------------------------------------
// 引入
// -----------------------------------------------------------------------------

include "../config/config.php";
include "../auth.php";
include "../DBManager.php";

// -----------------------------------------------------------------------------
// 访问设置
// -----------------------------------------------------------------------------

if (!isset($_GET['categoryId'])) {
    exit("需要传入有效的参数！");
}

$categoryId = $_GET['categoryId'];

if (isset($_GET['linkId'])) {
    $linkId = $_GET['linkId'];
} else {
    $linkId = "null";
}

// -----------------------------------------------------------------------------
// 数据库相关设置
// -----------------------------------------------------------------------------

$dbPath = "../" . $dbPath;
$db = new DBManager("sqlite:" . $dbPath);

// -----------------------------------------------------------------------------

$categories = $db->getListOfCategories();
$categoryDetail = $db->getCategoryDetailsById($categoryId)

// -----------------------------------------------------------------------------
?>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>网址管理</title>
    <link rel="stylesheet" href="../resources/bootstrap-5.2.0-beta1-dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="../resources/bootstrap-icons-1.5.0/bootstrap-icons.css">
    <link rel="stylesheet" href="../global.css">
</head>
<body>

<!-- ----------------------------------------------------------------------- -->

<script src="../resources/bootstrap-5.2.0-beta1-dist/js/bootstrap.min.js"></script>
<script src="../resources/jQuery/jquery-3.5.1.js"></script
<?php include "../globalNavbar.php"; ?>

<!-- ----------------------------------------------------------------------- -->

<!-- div:container start -->
<div class="mainContainer container container-fluid mb-5">

    <!-- 导航栏 开始 -->
    <div class="mt-3">
        <nav style="--bs-breadcrumb-divider: '>';" aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a class="text-decoration-none" href="<?php echo $homepage; ?>">首页</a></li>
                <li class="breadcrumb-item active"><a class="text-decoration-none" href="index.php">分类管理</a></li>
                <li class="breadcrumb-item active text-break"><?php echo $categoryDetail["title"]; ?></li>
            </ol>
        </nav>
    </div>
    <!-- 导航栏 结束 -->

    <div class="mt-2">
        <div class="card">
            <div class="card-header">
                <span>
                    <span type="button" class="badge text-bg-dark mx-1 my-1 btnCreateLink">新建链接<span style="font-size: 0.75em">(alt 1)</span></span>
                    <span type="button" class="badge text-bg-dark mx-1 my-1 btnCreateLinkInQuantity">批量新建链接<span style="font-size: 0.75em">(alt 2)</span></span>
                    <span type="button" class="badge text-bg-dark mx-1 my-1 btnViewNav">导航<span style="font-size: 0.75em">(alt 3)</span></span>
                </span>
            </div>
        </div>
    </div>

    <!--链接列表 开始-->
    <div id="list" class="mt-2 mb-2">
    </div>
    <!--链接列表 结束-->

</div>
<!-- div:container end -->

<!-- ----------------------------------------------------------------------- -->

<!-- Modal 创建 Link 开始 -->
<div class="modal fade" id="modalCreateLink" data-bs-backdrop="true" data-bs-keyboard="true" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header">
                <h1 class="modal-title fs-5" id="staticBackdropLabel">新建链接</h1>
                <button type="button" id="btnCloseModalCreateLink" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">

                <form id="formCreateLink" action="createLinkFormAction.php" method="post" class="mb-0">

                    <fieldset class="mt-0">

                        <input type="text"
                               id="inputTargetSortNumber"
                               name="targetSortNumber"
                               style="display: none">

                        <!--网站标题-->
                        <div class="mt-0">
                            <input type="text"
                                   id="inputLinkTitle"
                                   name="linkTitle"
                                   required
                                   autocomplete="off"
                                   placeholder="标题"
                                   class="form-control">
                        </div>

                        <!--网站链接-->
                        <div class="mt-2">
                            <input type="url"
                                   id="inputLinkUrl"
                                   name="linkUrl"
                                   required
                                   autocomplete="off"
                                   placeholder="网址，别忘了 https:// 前缀"
                                   class="form-control">
                        </div>

                        <!--所属分类-->
                        <div class="mt-2">
                            <select name="categoryId"
                                    id="selectCategoryId"
                                    class="form-select"
                                    required>
                                <?php
                                    foreach ($categories as $category) {
                                        $tempCategoryId = $category['id'];
                                        $tempCategoryTitle = $category['title'];

                                        if ($tempCategoryId == $categoryId) {
                                            echo "<option value='$tempCategoryId' selected>$tempCategoryTitle</option>";
                                        } else {
                                            echo "<option value='$tempCategoryId'>$tempCategoryTitle</option>";
                                        }
                                    }
                                ?>
                            </select>
                        </div>

                        <!--描述-->
                        <div class="mt-2">
                            <textarea name="linkDescription"
                                      id="inputLinkDescription"
                                      cols="30"
                                      rows="10"
                                      placeholder="请输入描述。按 Ctrl + s 保存。"
                                      class="form-control"></textarea>
                        </div>

                    </fieldset>

                    <fieldset class="mt-3">
                        <button id="btnConfirmCreateLink" type="button" class="btn btn-outline-primary">保存</button>
                        <button id="btnClearFormCreateLink" type="button" class="btn btn-outline-secondary">清空</button>
                    </fieldset>

                </form>

            </div>

        </div>
    </div>
</div>
<!-- Modal 创建 Link 结束 -->

<!-- ----------------------------------------------------------------------- -->

<!--Modal 管理 Link 开始-->
<div class="modal fade" id="modalManageLink" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel">要执行哪项操作呢？当前链接：<span id="titleOfLinkToManage" class="text-info text-break"></span></h1>
                <button id="btnCloseModalManageLink" type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">

                <div class="input-group mt-0">

                    <select name="targetCategoryId" id="selectTargetCategoryId" class="form-select mt-0">
                        <?php
                        foreach ($categories as $category) {
                            $tempCategoryId = $category['id'];
                            $tempCategoryTitle = $category['title'];

                            if ($tempCategoryId == $categoryId) {
                                echo "<option value='$tempCategoryId' selected>$tempCategoryTitle</option>";
                            } else {
                                echo "<option value='$tempCategoryId'>$tempCategoryTitle</option>";
                            }
                        }
                        ?>
                    </select>
                    <button id="btnMoveLink" class="btn btn-outline-secondary mt-0">转移</button>

                </div>

                <div class="list-group mt-1">
                    <button id="btnViewLink" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-eye"></i></span>
                        详情
                    </button>
                    <button id="btnEditLink" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-pencil-square"></i></span>
                        编辑
                    </button>
                    <button id="btnDeleteLink" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-trash"></i></span>
                        删除
                    </button>
                </div>

                <div class="list-group mt-1">
                    <button id="btnCreateLinkAbove" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-file-earmark-arrow-up"></i></span>
                        上方新建链接
                    </button>
                    <button id="btnCreateLinkBelow" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-file-earmark-arrow-down"></i></span>
                        下方新建链接
                    </button>
                </div>

                <div class="list-group mt-1">
                    <button id="btnMoveLinkTopOf" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-arrow-bar-up"></i></span>
                        移动到指定链接的上方
                    </button>
                    <button id="btnMoveLinkUnder" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-arrow-bar-down"></i></span>
                        移动到指定链接的下方
                    </button>
                    <button id="btnMoveUpLink" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-arrow-up"></i></span>
                        上移
                    </button>
                    <button id="btnMoveDownLink" class="list-group-item list-group-item-action">
                        <span class="icon"><i class="bi bi-arrow-down"></i></span>
                        下移
                    </button>
                </div>

            </div>

        </div>
    </div>
</div>
<!--Modal 管理 Link 结束-->

<!-- ----------------------------------------------------------------------- -->

<!--Modal 查看 link 详情 开始-->
<div class="modal fade" id="modalViewLink" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable">
        <div class="modal-content">

            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel">查看链接详情</h1>
                <button id="btnCloseModalViewLink" type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">
                <div id="linkDetails"></div>
            </div>

        </div>
    </div>
</div>
<!--Modal 查看 link 详情 结束-->

<!-- ----------------------------------------------------------------------- -->

<!-- Modal 编辑 Link 开始 -->
<div class="modal fade" id="modalEditLink" data-bs-backdrop="true" data-bs-keyboard="true" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header">
                <h1 class="modal-title fs-5" id="staticBackdropLabel">编辑链接</h1>
                <button type="button" id="btnCloseModalEditLink" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">

                <form id="formEditLink" action="editLinkFormAction.php" method="post" class="mb-0">

                    <fieldset class="mt-0">

                        <!--隐藏的输入框，存放链接id-->
                        <input id="editLinkId" name="linkId" type="hidden">

                        <!--网站标题-->
                        <div class="mt-0">
                            <input type="text"
                                   id="editLinkTitle"
                                   name="linkTitle"
                                   required
                                   autocomplete="off"
                                   placeholder="标题"
                                   class="form-control">
                        </div>

                        <!--网站链接-->
                        <div class="mt-2">
                            <input type="url"
                                   id="editLinkUrl"
                                   name="linkUrl"
                                   required
                                   autocomplete="off"
                                   placeholder="网址，别忘了 https:// 前缀"
                                   class="form-control">
                        </div>

                        <!--所属分类-->
                        <div class="mt-2">
                            <select name="categoryId"
                                    id="editCategoryId"
                                    class="form-select"
                                    required>
                                <?php
                                foreach ($categories as $category) {
                                    $tempCategoryId = $category['id'];
                                    $tempCategoryTitle = $category['title'];

                                    if ($tempCategoryId == $categoryId) {
                                        echo "<option value='$tempCategoryId' selected>$tempCategoryTitle</option>";
                                    } else {
                                        echo "<option value='$tempCategoryId'>$tempCategoryTitle</option>";
                                    }
                                }
                                ?>
                            </select>
                        </div>

                        <!--描述-->
                        <div class="mt-2">
                            <textarea name="linkDescription"
                                      id="editLinkDescription"
                                      cols="30"
                                      rows="10"
                                      placeholder="描述。按 Ctrl + s 保存。"
                                      class="form-control"></textarea>
                        </div>

                    </fieldset>

                    <fieldset class="mt-3">
                        <button id="btnConfirmEditLink" type="button" class="btn btn-outline-primary">保存</button>
                        <button id="btnClearFormEditLink" type="button" class="btn btn-outline-secondary">清空</button>
                    </fieldset>

                </form>

            </div>

        </div>
    </div>
</div>
<!-- Modal 编辑 Link 结束 -->

<!-- ----------------------------------------------------------------------- -->

<!-- Modal 确认删除 Link 开始 -->
<div class="modal fade" id="modalConfirmDeleteLink" data-bs-backdrop="true" data-bs-keyboard="true" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header">
                <h1 class="modal-title fs-5" id="staticBackdropLabel">提示</h1>
                <button type="button" id="btnCloseModalConfirmDeleteLink" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">
                <p>确定要删除吗？当前链接：<span id="titleOfLinkToDelete" class="text-info text-break"></span></p>
                <p class="mb-0">删除之后，<span class="text-danger">无法撤消</span>，请谨慎选择。</p>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                <button id="btnConfirmDeleteLink" type="button" class="btn btn-outline-primary">确定</button>
            </div>

        </div>
    </div>
</div>
<!-- Modal 确认删除 Link 结束 -->

<!-- ----------------------------------------------------------------------- -->

<!-- Modal 选择要移动哪个链接的上方 开始 -->
<div class="modal fade" id="modalSelectTargetLink" data-bs-backdrop="true" data-bs-keyboard="true" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable">
        <div class="modal-content">

            <div class="modal-header">
                <h1 class="modal-title fs-5" id="titleSelectTargetLink"></h1>
                <button type="button" id="btnCloseModalSelectTargetLink" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body" id="listOfTargetLinks">
            </div>

        </div>
    </div>
</div>
<!-- Modal 选择要移动哪个链接的上方 结束 -->

<!----------------------------------------------------------------------------->

<!--Toast 消息弹窗 开始-->
<div aria-live="polite" aria-atomic="true" class="position-relative">
    <div class="toast-container position-fixed top-0 start-50 translate-middle-x">

        <div id="toastShowMessage" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div id="toastHeader" class="toast-header bg-info">
                <strong class="me-auto">提示</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body bg-white">
                <p id="msgContent">需要显示的信息。</p>
            </div>
        </div>

    </div>
</div>
<!--Toast 消息弹窗 结束-->

<!----------------------------------------------------------------------------->

<!--全局变量-->
<script>
    let titleOfLinkToManage = "";

    let idOfLinkToManage = "";
    let idOfPreLink = "";
    let idOfNextLink = "";

    let sortNumberOfLinkToManage = "";
    let sortNumberOfPreLink = "";
    let sortNumberOfNextLink = "";

    let createLinkInQuantity = false;

    let moveAction = "";

    let idOfSpecifiedLink = "<?php echo $linkId; ?>";
</script>

<!----------------------------------------------------------------------------->

<!--函数定义-->
<script>
    // 通过 ajax 生成链接列表
    function getLists() {
        var url = `listOfLinksGenerator.php?categoryId=<?php echo $categoryId; ?>&linkId=${idOfSpecifiedLink}`;
        $.get(url)
            .done(function(data ) {
                $("#list").html(data)
                smoothScrollToId(idOfSpecifiedLink); // 方便从搜索结果页中跳转到此页面时，自动定位相应的链接
            })
            .fail(function () {
                alert("获取列表失败。")
            });
    }

    // 平滑滚动页面到指定元素
    function smoothScrollToId(targetId) {
        const targetElement = document.getElementById(targetId);

        if (!targetElement) {
            console.error(`Element with ID "${targetId}" not found`);
            return;
        }

        // 计算偏移后的位置
        const targetPosition = targetElement.getBoundingClientRect().top + window.pageYOffset;

        // 使用原生方法平滑滚动
        window.scrollTo({
            top: targetPosition,
            behavior: 'smooth'
        });
    }

</script>

<!----------------------------------------------------------------------------->

<!--网页加载时执行-->
<script>
    $(function () {
        getLists(); // 网页加载时，自动生成链接列表
    })
</script>

<!----------------------------------------------------------------------------->

<!--事件处理-->
<script>
    // 点击 链接右侧的「管理」按钮 时执行
    $(document).on("click", ".btnManageLink", function(e) {

        e.stopPropagation()
        e.preventDefault()

        titleOfLinkToManage = $(this).data("title")

        idOfLinkToManage = $(this).data("id")
        idOfPreLink = $(this).parent().parent().prev().children().last().children().last().data("id")
        idOfNextLink = $(this).parent().parent().next().children().last().children().last().data("id")

        sortNumberOfLinkToManage = $(this).data("sortnumber")
        sortNumberOfPreLink = $(this).parent().parent().prev().children().last().children().last().data("sortnumber")
        sortNumberOfNextLink = $(this).parent().parent().next().children().last().children().last().data("sortnumber")

        $("#titleOfLinkToManage").html(titleOfLinkToManage)

        /* 启用或禁用上下移动按钮 */

        if (sortNumberOfPreLink == undefined) {
            $("#btnMoveUpLink").attr("disabled", "disabled")
        } else {
            $("#btnMoveUpLink").removeAttr("disabled")
        }

        if (sortNumberOfNextLink == undefined) {
            $("#btnMoveDownLink").attr("disabled", "disabled")
        } else {
            $("#btnMoveDownLink").removeAttr("disabled")
        }

        /* 显示 Modal */
        const myModal = new bootstrap.Modal($("#modalManageLink"), {
            backdrop: true,
            keyboard: true
        })
        myModal.show()

    })
</script>

<!-- ----------------------------------------------------------------------- -->

<!--上方新建，下方新建-->
<script>
    // 上方新建
    $("#btnCreateLinkAbove").on("click", function () {
        $("#inputTargetSortNumber").val(sortNumberOfLinkToManage)
        const myModal = new bootstrap.Modal($("#modalCreateLink"), {
            backdrop: "static",
            keyboard: true
        })
        myModal.show()

        $("#btnCloseModalManageLink").click()
    })

    // 下方新建
    $("#btnCreateLinkBelow").on("click", function () {
        $("#inputTargetSortNumber").val(sortNumberOfNextLink)
        const myModal = new bootstrap.Modal($("#modalCreateLink"), {
            backdrop: "static",
            keyboard: true
        })
        myModal.show()

        $("#btnCloseModalManageLink").click()
    })
</script>

<!----------------------------------------------------------------------------->

<!--新建网址-->
<script>
    // 点击「新建链接」时执行
    $(".btnCreateLink").on("click", function () {

        $("#inputTargetSortNumber").val("")

        const myModal = new bootstrap.Modal($("#modalCreateLink"), {
            backdrop: "static",
            keyboard: true
        })
        myModal.show()

    })

    // 点击「批量新建链接」时执行
    $(".btnCreateLinkInQuantity").on("click", function () {
        createLinkInQuantity = true;
        $(".btnCreateLink").click()
    })

    // modal 弹出时，自动聚焦 title 输入框
    $('#modalCreateLink').on('shown.bs.modal', function () {
        $('#inputLinkTitle').focus();
    });

    // 点击新建分类modal中的「清空」按钮时执行
    $("#btnClearFormCreateLink").on("click", function (e) {
        $("#inputLinkTitle").val("")
        $("#inputLinkUrl").val("")
        $("#inputLinkDescription").val("")
        $("#inputLinkTitle").focus()
    })

    // 按下 ctrl + s 时保存。
    // 参考资料：https://stackoverflow.com/questions/93695/best-cross-browser-method-to-capture-ctrls-with-jquery
    $("#inputLinkTitle, #inputLinkUrl, #inputLinkDescription, #selectCategoryId").bind('keydown', function(event) {
        if (event.ctrlKey || event.metaKey) {
            switch ((event.key).toLowerCase()) {
                case 's':
                    event.preventDefault();
                    $("#btnConfirmCreateLink").click();
            }
        }
    });

    // 点击 新建Link modal 中的「确认」按钮 时执行
    $("#btnConfirmCreateLink").on("click", function (e) {

        let linkTitle = $("#inputLinkTitle").val().trim()
        let linkUrl = $("#inputLinkUrl").val().trim()
        let categoryId = $("#selectCategoryId").val().trim()

        if (linkTitle == "" || linkUrl == "" || categoryId == "") {

            alert("需要输入有效的数据！")

        } else {

            const url = "createLinkFormAction.php";

            $.post(url, $("#formCreateLink").serialize())
                .done(function (data) {

                    // 清空输入框
                    $("#inputLinkTitle").val("")
                    $("#inputLinkUrl").val("")
                    $("#inputLinkDescription").val("")

                    if (createLinkInQuantity) {
                        $("#inputLinkTitle").focus()
                    } else {
                        // 关闭新建链接 modal
                        $("#btnCloseModalCreateLink").click()
                    }

                    $("#msgContent").text(data)
                    $("#toastHeader").attr("class", "toast-header bg-info")
                    const toast = new bootstrap.Toast(toastShowMessage, {"delay": 1500})
                    toast.show()

                })
                .fail(function () {
                    alert("保存失败！")
                })

        }
    })

    // modal 关闭时，取消批量新建网址，并刷新网址列表
    $('#modalCreateLink').on('hidden.bs.modal', function () {
        createLinkInQuantity = false

        // 清空未保存的输入数据
        $("#inputLinkTitle").val("")
        $("#inputLinkUrl").val("")
        $("#inputLinkDescription").val("")

        getLists()
    });

</script>

<!----------------------------------------------------------------------------->

<!--移动到指定链接的上方或下方-->
<script>

    function openListOfTargetLink() {
        const url = `listOfTargetLinksGenerator.php?categoryId=<?php echo $categoryId; ?>`
        $.get(url)
            .done(function(data) {

                // 关闭 modal
                $("#btnCloseModalManageLink").click()

                $("#listOfTargetLinks").html(data)

                const myModal = new bootstrap.Modal($("#modalSelectTargetLink"), {
                    backdrop: true,
                    keyboard: true
                })
                myModal.show()

            })
            .fail(function () {
                alert("请求列表失败！")
            });
    }

    $("#btnMoveLinkTopOf").on("click", function (e) {
        moveAction = "top"
        $("#titleSelectTargetLink").html("希望移动到哪个链接的<span class='text-info'>上方</span>呢？")
        openListOfTargetLink()
    })

    $("#btnMoveLinkUnder").on("click", function (e) {
        moveAction = "under"
        $("#titleSelectTargetLink").html("希望移动到哪个链接的<span class='text-info'>下方</span>呢？")
        openListOfTargetLink()
    })

    $(document).on("click", ".selectAsTarget", function(e) {

        let sortNumberOfTargetLink = ""
        let action = ""

        switch (moveAction) {
            case "top":

                sortNumberOfTargetLink = $(this).data("sortnumber")
                action = "top"

                if ($(this).data("sortnumber") == sortNumberOfLinkToManage) {
                    $(this).addClass("disabled")
                    $(this).css("color", "red")
                    alert("选中的这个链接，是你当前正想要移动的。请重新选择！")
                    return; // 跳出当前函数
                }

                if ($(this).data("sortnumber") == sortNumberOfNextLink) {
                    $(this).addClass("disabled")
                    $(this).css("color", "red")
                    alert("移动之后，还是在当前位置，请重新选择！")
                    return;
                }

                break;
            case "under":

                // 顺序排列的列表，移动到最下方一个分区的下方时，这里获取到的值是 undefined。
                sortNumberOfTargetLink = $(this).next().data("sortnumber")
                action = "under"

                if ($(this).data("sortnumber") == sortNumberOfLinkToManage) {
                    $(this).addClass("disabled")
                    $(this).css("color", "red")
                    alert("选中的这个链接，是你当前正想要移动的。请重新选择！")
                    return; // 跳出当前函数
                }

                if ($(this).data("sortnumber") == sortNumberOfPreLink) {
                    $(this).addClass("disabled")
                    $(this).css("color", "red")
                    alert("移动之后，还是在当前位置，请重新选择！")
                    return; // 跳出当前函数
                }

        }

        const url = `changeSortNumberOfLinkFromAToB.php?source=${sortNumberOfLinkToManage}&target=${sortNumberOfTargetLink}&action=${action}`

        $.get(url)
            .done(function(data) {

                // 关闭 modal
                $("#btnCloseModalSelectTargetLink").click()
                getLists()

            })
            .fail(function () {
                alert("移动失败！")
            });

    })
</script>

<!----------------------------------------------------------------------------->

<!--上下移动网址-->
<script>
    // 上移
    $("#btnMoveUpLink").on("click", function (e) {

        // 关闭 管理 modal
        $("#btnCloseModalManageLink").click();

        let idOne = idOfLinkToManage;
        let sortNumberOne = sortNumberOfLinkToManage;

        let idTwo = idOfPreLink;
        let sortNumberTwo = sortNumberOfPreLink;

        if (idTwo !== undefined) {

            let url = `changeSortNumberOfLink.php?idOne=${idOne}&idTwo=${idTwo}&sortNumberOne=${sortNumberOne}&sortNumberTwo=${sortNumberTwo}`;

            $.get(url)
                .done(function(data ) {
                    getLists()
                })
                .fail(function () {
                    alert("请求列表失败。")
                });

        }

    })

    // 下移
    $("#btnMoveDownLink").on("click", function (e) {

        // 关闭 管理 modal
        $("#btnCloseModalManageLink").click();

        let idOne = idOfLinkToManage;
        let sortNumberOne = sortNumberOfLinkToManage;

        let idTwo = idOfNextLink;
        let sortNumberTwo = sortNumberOfNextLink;

        if (idTwo !== undefined) {

            let url = `changeSortNumberOfLink.php?idOne=${idOne}&idTwo=${idTwo}&sortNumberOne=${sortNumberOne}&sortNumberTwo=${sortNumberTwo}`;

            $.get(url)
                .done(function(data ) {
                    getLists()
                })
                .fail(function () {
                    alert("请求列表失败。")
                });

        }

    })
</script>

<!----------------------------------------------------------------------------->

<!--删除网址-->
<script>
    // 点击 管理面板中的「删除」按钮 时执行
    $("#btnDeleteLink").on("click", function () {
        // 关闭 管理 modal
        $("#btnCloseModalManageLink").click()

        $("#titleOfLinkToDelete").html(titleOfLinkToManage)

        /* 显示 确认删除 Modal */
        const myModal = new bootstrap.Modal($("#modalConfirmDeleteLink"), {
            backdrop: true,
            keyboard: true
        })
        myModal.show()
    })

    // 点击 删除确认弹窗中的「确认」按钮 时执行
    $("#btnConfirmDeleteLink").on("click", function () {

        // 关闭 删除确认 modal
        $("#btnCloseModalConfirmDeleteLink").click()

        // 执行删除
        let url = `deleteLink.php?id=${idOfLinkToManage}`
        $.get(url)
            .done(function(data ) {
                getLists()
            })
            .fail(function () {
                alert("删除失败。")
            });

    })
</script>

<!----------------------------------------------------------------------------->

<!--编辑网址-->
<script>
    // 点击 管理弹窗中的「编辑」按钮 时执行
    $("#btnEditLink").on("click", function () {

        // 关闭 管理 modal
        $("#btnCloseModalManageLink").click()

        // 请求链接信息
        let url = `editLink.php?id=${idOfLinkToManage}`

        $.get(url)
            .done(function(data ) {

                // 初始化 编辑链接 modal
                let jsonObj =JSON.parse(data)

                $("#editLinkId").val(idOfLinkToManage)
                $("#editLinkTitle").val(jsonObj.title)
                $("#editLinkUrl").val(jsonObj.url)
                $("#editCategoryId").val(jsonObj.categoryId)
                $("#editLinkDescription").val(jsonObj.description)

                // 弹出 编辑链接 modal
                const myModal = new bootstrap.Modal($("#modalEditLink"), {
                    backdrop: "static",
                    keyboard: true
                })
                myModal.show()

            })
            .fail(function () {
                alert("获取链接详情失败。")
            });

    })

    // modal 弹出时，自动聚焦 title 输入框
    $('#modalEditLink').on('shown.bs.modal', function () {
        $('#editLinkTitle').focus();
    });

    // 点击 编辑链接 modal 中的「清空」按钮 时执行
    $("#btnClearFormEditLink").on("click", function (e) {
        $("#editLinkTitle").val("")
        $("#editLinkUrl").val("")
        $("#editLinkDescription").val("")
        $("#editLinkTitle").focus()
    })

    // 按下 ctrl + s 时保存。
    // 参考资料：https://stackoverflow.com/questions/93695/best-cross-browser-method-to-capture-ctrls-with-jquery
    $("#editLinkTitle, #editLinkUrl, #editCategoryId, #editLinkDescription").bind('keydown', function(event) {
        if (event.ctrlKey || event.metaKey) {
            switch ((event.key).toLowerCase()) {
                case 's':
                    event.preventDefault();
                    $("#btnConfirmEditLink").click();
            }
        }
    });

    // 点击 链接编辑 modal 中的「保存」按钮 时执行
    $("#btnConfirmEditLink").on("click", function () {

        let linkTitle =$("#editLinkTitle").val().trim()
        let linkUrl = $("#editLinkUrl").val().trim()
        let categoryId = $("#editCategoryId").val().trim()

        if (linkTitle == "" || linkUrl == "" || categoryId == "") {
            alert("需要输入有效的数据！")
        } else {
            // 标题不为空

            const url = "editLinkFormAction.php"

            $.post(url, $("#formEditLink").serialize())
                .done(function (data) {

                    // 关闭 分类编辑 modal
                    $("#btnCloseModalEditLink").click()

                    getLists()

                    $("#msgContent").text(data)
                    $("#toastHeader").attr("class", "toast-header bg-info")
                    const toast = new bootstrap.Toast(toastShowMessage, {"delay": 1500})
                    toast.show()

                })
                .fail(function () {
                    alert("保存失败！")
                })

        }

    })
</script>

<!----------------------------------------------------------------------------->

<!--移动网址-->
<script>

    $("#btnMoveLink").on("click", function (e) {

        $("#btnCloseModalManageLink").click()

        const linkId = idOfLinkToManage;
        const targetCategoryId = $("#selectTargetCategoryId").val();
        const url = `moveLink.php?linkId=${linkId}&targetCategoryId=${targetCategoryId}`;

        $.get(url)
            .done(function(data ) {
                getLists()
            })
            .fail(function () {
                alert("转移失败。")
            });

    })

</script>

<!----------------------------------------------------------------------------->

<!--查看链接详情-->
<script>
    $("#btnViewLink").on("click", function () {

        $("#btnCloseModalManageLink").click()
        const linkId = idOfLinkToManage;
        const url = `viewLink.php?id=${linkId}`

        $.get(url)
            .done(function(data ) {

                // 初始化 链接详情 modal
                $("#linkDetails").html(data)

                // 弹出 链接详情 modal
                const myModal = new bootstrap.Modal($("#modalViewLink"), {
                    backdrop: true,
                    keyboard: true
                })
                myModal.show()

            })
            .fail(function () {
                alert("获取链接详情失败。")
            });

    })
</script>

<!----------------------------------------------------------------------------->

<!--网址点击统计-->
<script>
    $(document).on("click", ".openLink", function(e) {
        // 阻止打开链接
        e.preventDefault()

        // 记录点击
        const linkUrl = $(this).prop("href")
        const linkId = $(this).children().last().children().last().data("id")
        const linkTitle = $(this).children().last().children().last().data("title")

        const url = "../clickLog.php";

        $.ajax({
            method: "POST",
            url: url,
            async: false,
            data: { linkId: linkId, linkUrl: linkUrl, linkTitle: linkTitle }
        })
            .done(function( msg ) {
                // 点击记录成功

                // 刷新网址列表，主要是为了刷新网址点击数
                getLists()

                // 打开链接
                window.open(linkUrl, "_blank")
            })
            .fail(function( jqXHR, textStatus ) {
                alert("点击记录失败！")
            });

    })
</script>

<!----------------------------------------------------------------------------->

<script>
    $(".btnViewNav").on("click", function () {
        let url = `../nav.php?categoryId=<?php echo $categoryId; ?>`
        window.open(url, "_self")
    })
</script>

<!----------------------------------------------------------------------------->

<!-- 添加「返回顶部按钮」 -->
<script src="../resources/vanilla-back-to-top/index.js"></script>
<script src="../resources/vanilla-back-to-top/config.js"></script>

<!----------------------------------------------------------------------------->

<script>
    // 为便于从旧版的网址导航程序中迁移数据，新增功能：
    // 新建网址时，在「标题」输入框中粘贴形如 "xxx": "xxx" 的字符串，系统会自动将其分割为链接 title 与 url
    $("#inputLinkTitle").on("keyup", function () {
        let userInput = $("#inputLinkTitle").val()
        if (userInput.includes(".")) {
            let arr = userInput.split(":")
            const linkTitle = arr[0].trim().slice(1).slice(0, -1) // 取得链接 title
            const urlStart = arr[1].trim().slice(1)
            let urlEnd = ""
            if (arr[2].trim().endsWith(",")) {
                urlEnd = arr[2].trim().slice(0, -2)
            } else {
                urlEnd = arr[2].trim().slice(0, -1)
            }
            const linkUrl = urlStart + ":" + urlEnd // 取得链接 url
            $("#inputLinkTitle").val(linkTitle)
            $("#inputLinkUrl").val(linkUrl)
            $("#btnConfirmCreateLink").click()
        }
    })
</script>

<!----------------------------------------------------------------------------->

<!--快捷键-->
<script>

    $(document).keydown(function(event){
        // 查看更多 keycode，参考：https://www.toptal.com/developers/keycode
        if (event.altKey) {
            switch (event.key) {
                case "1":
                    // 点击「新建链接」按钮
                    event.preventDefault();
                    $(".btnCreateLink").click();
                    break;
                case "2":
                    // 点击「批量新建链接」按钮
                    event.preventDefault();
                    $(".btnCreateLinkInQuantity").click();
                    break;
                case "3":
                    // 点击「导航」按钮
                    event.preventDefault();
                    $(".btnViewNav").click();
                    break;
            }
        }
    })

</script>

<!----------------------------------------------------------------------------->

</body>
</html>
